package net.hn.hnms.biz.safety.monitor.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.feign.model.DataStateVo;
import net.hn.hnms.biz.api.mine.model.AlarmMessageItemVo;
import net.hn.hnms.biz.api.safety.gasext.fegin.RemoteDwsService;
import net.hn.hnms.biz.api.safety.location.model.OutLimitAlarmingInfoVO;
import net.hn.hnms.biz.api.safety.monitor.model.*;
import net.hn.hnms.biz.api.safety.water.model.SubsidenceAnalysisVo;
import net.hn.hnms.biz.common.jpa.utils.ResponsePage;
import net.hn.hnms.biz.safety.monitor.domain.*;
import net.hn.hnms.biz.safety.monitor.repository.AqjkDictEntityRepository;
import net.hn.hnms.biz.safety.monitor.service.SafetyMonitorService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import net.hn.hnms.sys.common.satoken.config.AutoSetMineCode;
import org.springframework.data.domain.PageRequest;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 智呈物联 pan'sx
 * 2022/7/26 16:24
 * 1.0 version
 */
@RestController
@RequestMapping("riskMonitor/gas")
@Api(value = "安全监控控制器", tags = {"安全监控"})
@RequiredArgsConstructor
public class RiskMonitorController {
    private final SafetyMonitorService safetyMonitorService;
    private final AqjkDictEntityRepository aqjkDictEntityRepository;


    @Resource
    private RemoteDwsService remoteDwsService;

    @GetMapping("todayInfo")
    @ApiOperation("今日信息")
    @AutoSetMineCode
    public R<MonitorTodayInfo> todayInfo(String mineCode) {
        return R.ok(safetyMonitorService.getTodayInfo(mineCode));
    }

    @GetMapping("keyAreas")
    @ApiOperation("关键区域")
    @AutoSetMineCode
    public R<List<KeyAreasVo>> keyAreas(@ApiParam(value = "区域id", required = true) String areaId, String mineCode) {
        return R.ok(safetyMonitorService.keyAreas(areaId, mineCode));
    }

    @GetMapping("alarmTrend")
    @ApiOperation("报警趋势")
    @AutoSetMineCode
    public R<AlarmTrendVo> alarmTrend(String mineCode) {
        return R.ok(safetyMonitorService.alarmTrend(mineCode,"周"));
    }

    @GetMapping("safetyMonitor")
    @ApiOperation("安全监测")
    @AutoSetMineCode
    public R<List<SafetyMonitorVo>> safetyMonitor(String mineCode) {

        return R.ok(safetyMonitorService.safetyMonitor(mineCode));
    }

    @GetMapping("pointStatistics")
    @ApiOperation("测点统计")
    @AutoSetMineCode
    public R<List<PointStatistics>> pointStatistics(String mineCode) {
        return R.ok(safetyMonitorService.pointStatistics(mineCode));
    }

    @GetMapping("indicator")
    @ApiOperation("重要指标")
    @AutoSetMineCode
    public R<Indicator> indicator(String mineCode) {

        return R.ok(safetyMonitorService.indicator(mineCode));
    }

    @GetMapping("sensorAlarmPage/pageList")
    @ApiOperation("数据查询-报警明细列表")
    @AutoSetMineCode
    public R<ResponsePage<SensorAlarmEntity>> sensorAlarmPage(@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "20") int pageSize, String sensorType, String outlierType, String beginTime, String endTime, String mineCode) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return R.ok(safetyMonitorService.sensorAlarmPage(pageRequest, sensorType, outlierType, beginTime, endTime, mineCode));
    }

    @GetMapping("aqjkDict")
    @ApiOperation("安全监控字典接口")
    public R<List<AqjkDictVo>> aqjkDict(@ApiParam(value = "字典类型  检测类型：aqjk_sensor_type 报警类型:aqjk_alarm  传感器状态：point_status", required = true) String type) {
        List<AqjkDictEntity> byType = aqjkDictEntityRepository.findByType(type);
        List<AqjkDictVo> collect = byType.stream().map(aqjkDictEntity -> {
            AqjkDictVo vo = new AqjkDictVo();
            vo.setLabel(aqjkDictEntity.getSimpleName());
            vo.setValue(aqjkDictEntity.getPointLoactionName());
            return vo;
        }).collect(Collectors.toList());
        return R.ok(collect);
    }

    @GetMapping("sensorMonitorNow/pageList")
    @ApiOperation("数据查询-实时数据")
    @AutoSetMineCode
    public R<ResponsePage<AqjkNowSensorMonitorEntity>> sensorMonitorNow(@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "20") int pageSize, String pointLocation, String sensorType, String status, String mineCode) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return R.ok(safetyMonitorService.sensorMonitorNow(pageRequest, pointLocation,sensorType, status, mineCode));
    }

    @GetMapping("trendByPointCode")
    @ApiOperation("数据查询-测点值时间图")
    @AutoSetMineCode
    public R<List<AqjkHisSensorMonitorEntity>> trendByPointCode(@RequestParam(required = true) String pointCode,
                                                                @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME, pattern = "yyyy-MM-dd HH:mm:ss") @ApiParam(example = "yyyy-MM-dd HH:mm:ss  默认结束时间前推6小时") Date beginTime,
                                                                @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME, pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = true) @ApiParam(example = "yyyy-MM-dd HH:mm:ss", required = true) Date endTime, String mineCode) {
        if (beginTime != null) {
            if (endTime.getTime() - beginTime.getTime() > 3600 * 6 * 1000) {
                return R.fail("时间区间不能大于6小时");
            }
        }
        return R.ok(safetyMonitorService.findByPointCodeAndDataTimeBetween(pointCode, beginTime, endTime,mineCode));
    }

    @GetMapping("pointExceptionRecordDataList")
    @ApiOperation("数据查询-弹出框——异常数据")
    @AutoSetMineCode
    public R<List<SensorAlarmEntity>> pointDataList(@RequestParam(required = true) String pointCode, @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME, pattern = "yyyy-MM-dd HH:mm:ss") @ApiParam(example = "yyyy-MM-dd HH:mm:ss  默认结束时间前推6小时") Date beginTime,
                                                    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME, pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(required = true) @ApiParam(example = "yyyy-MM-dd HH:mm:ss", required = true) Date endTime,String mineCode) {
        if (beginTime != null) {
            if (endTime.getTime() - beginTime.getTime() > 3600 * 6 * 1000) {
                return R.fail("时间区间不能大于6小时");
            }
        }
        return R.ok(safetyMonitorService.pointExceptionRecordDataList(pointCode, beginTime, endTime,mineCode));
    }

    @GetMapping("sensorMonitorHis/pageList")
    @ApiOperation("数据查询-历史数据")
    @AutoSetMineCode
    public R<ResponsePage<AqjkHisSensorMonitorEntity>> sensorMonitorHis(@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "20") int pageSize, String sensorType, String beginTime, String endTime, String loaction,String mineCode) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        return R.ok(safetyMonitorService.sensorMonitorHis(pageRequest, sensorType, beginTime, endTime, loaction,mineCode));
    }

    @GetMapping("baseSensorinfo/pageList")
    @ApiOperation("数据查询-监测器列表")
    @AutoSetMineCode
    public R<ResponsePage<AqjkNowBaseSensorinfoEntity>> baseSensorinfo(@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "20") int pageSize, String sensorType,
                                                                       String loaction, @ApiParam("是否查询实时数据，默认否") boolean currentValue, String mineCode) {
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        ResponsePage<AqjkNowBaseSensorinfoEntity> aqjkNowBaseSensorinfoEntityResponsePage = safetyMonitorService.baseSensorInfo(pageRequest, sensorType, loaction, currentValue,mineCode);
        aqjkNowBaseSensorinfoEntityResponsePage.getPageData().forEach(s -> {
            if ("KG".equals(s.getPointValueType()) || "BJ".equals(s.getPointValueType())) {
                if (s.getCurrentValue() != null) {
                    s.setCurrentValue(new BigDecimal(s.getCurrentValue()).longValue() + "");
                }
            }
        });
        return R.ok(aqjkNowBaseSensorinfoEntityResponsePage);
    }

    @GetMapping("trendBySensorCode")
    @ApiOperation(value = "查询监测值曲线图", notes = "sensorCode默认‘250203下综采二队工作面5至10米范围内温度’")
    @AutoSetMineCode
    public R<SensorValueTrendVo> trendBySensorCode(@RequestParam(defaultValue = "62082400973401MN0003000558")
                                                   @ApiParam(example = "62082400973401MN0003000558") String sensorCode, String mineCode) {
        return R.ok(safetyMonitorService.trendBySensorCode(sensorCode,mineCode));
    }

    @GetMapping("environmentalAwareness")
    @ApiOperation("环境感知")
    @AutoSetMineCode
    public R<List<SafetyMonitorVo>> environmentalAwareness(@ApiParam("x坐标") Double x, @ApiParam("y坐标") Double y, @ApiParam("z坐标") Double z,String mineCode) {
        return R.ok(safetyMonitorService.environmentalAwareness(x, y, z,mineCode));
    }

    @GetMapping("coalEarlyWarning")
    @ApiOperation("煤自燃分级预警")
    public R<SubsidenceAnalysisVo> coalEarlyWarning() {
        return R.ok(safetyMonitorService.coalEarlyWarning());
    }

    @GetMapping("alarmMessageItem")
    @ApiOperation("安全监控报警消息")
    @AutoSetMineCode
    public R<List<AlarmMessageItemVo>> alarmMessageItem(String mineCode) {
        return R.ok(safetyMonitorService.alarmMessageItem(mineCode));
    }
    @GetMapping("maxTime")
    @ApiOperation("数据最新时间")
    public R<List<DataStateVo>> getMaxTime(String mineCode, String companyCode){
        return R.ok(safetyMonitorService.getMaxTime( mineCode,companyCode));
    }

    /**
     * 获取当天报警超限信息
     */
    @GetMapping("alarmInfoList")
    @ApiOperation("获取当天报警超限信息")
    public R<List<OutLimitAlarmingInfoVO>> alarmInfoList(@ApiParam("公司编码") String companyCode,@ApiParam("煤矿编码") String mineCode) {
        Boolean istru = RedisUtils.getCacheObject(Constants.SYS_DWS_KEY);
        if (istru == null || !istru) {
            List<OutLimitAlarmingInfoVO> outLimitAlarmingInfoVOS = safetyMonitorService.alarmInfoList(mineCode);
            if (outLimitAlarmingInfoVOS.isEmpty()) {
                return R.ok(new ArrayList<>());
            }
            return R.ok(outLimitAlarmingInfoVOS);
        } else {
            List<OutLimitAlarmingInfoVO> data = remoteDwsService.alarmInfoList(companyCode,mineCode).getData();
            if (data.isEmpty()) {
                return R.ok(new ArrayList<>());
            }
            return R.ok(data);
        }

        }
}
